﻿#region

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Concrete.Security;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Security;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Services;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Validation.UserMembership;
using Tateeda.ClinicalStudy.Base.Modules.Lookups;
using Tateeda.ClinicalStudy.Base.Modules.Models.User;

#endregion

#region - Legal -

///<legal>
/// Copyright © 2011, Tateeda Media Network
/// All rights reserved. http://tateeda.com
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions
/// are met:
///
/// - Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
///
/// - Neither the name of the Tateeda Media Network, nor the names of its
/// contributors may be used to endorse or promote products
/// derived from this software without specific prior written
/// permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
/// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
/// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
/// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
/// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///</legal>

#endregion - Legal -

namespace Tateeda.ClinicalStudy.Base.Web.Controllers {

    public class UserController : Controller {
        private static int? _siteFilter;
        private readonly IUserService _service;

        public UserController(IUserService service) {
            _service = service;
        }

        public IFormsAuthenticationService FormsService { get; set; }

        public IMembershipService MembershipService { get; set; }

        public ActionResult Create() {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(AppUserModel user) {
            try {
                ValidateAppUserForm(user, false);
                if (ModelState.IsValid) {
                    // Attempt to register the user
                    var createStatus = MembershipService.CreateUser(user.UserName, user.Password, user.Email);
                    var newAccount = Membership.GetUser(user.UserName);

                    if (createStatus == MembershipCreateStatus.Success) {
                        FormsService.SignIn(user.UserName, false /* createPersistentCookie */);

                        //Assign to a role
                        var roleObj =
                            UtilLookup.RoleListLookup.Where(r => r.Value == user.RoleId.ToString()).FirstOrDefault();
                        if (roleObj != null) {
                            Roles.AddUserToRole(user.UserName, roleObj.Text);
                        }

                        string name = HttpContext.User.Identity.Name;
                        user.UpdatedBy = name;
                        user.CreatedBy = name;
                        user.UpdatedOn = DateTime.UtcNow;
                        user.CreatedOn = DateTime.UtcNow;
                        user = _service.CreateAppUser(user);
                        if (newAccount != null)
                            if (newAccount.ProviderUserKey != null)
                                user.UserId = new Guid(newAccount.ProviderUserKey.ToString());

                        _service.UpdateAppUser(user);
                        return RedirectToAction("Index");
                    }
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            } catch (Exception) {
            }
            return View(user);
        }

        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id) {
            _service.DeleteAppUser(id);
            return RedirectToAction("Index");
        }

        [ValidateAntiForgeryToken]
        public ActionResult Details(int id) {
            return View();
        }

        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id) {
            var appUserModel = _service.GetUser(id);

            return View(appUserModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(AppUserModel userModel) {
            try {
                ValidateAppUserForm(userModel, true);
                if (ModelState.IsValid) {
                    _service.UpdateAppUser(userModel);
                    return RedirectToAction("Index");
                }
            } catch (Exception ex) {
                ViewBag.Error = ex.InnerException == null ? ex.Message : ex.InnerException.Message;
            }

            return View(userModel);
        }

        /// <summary>
        ///   IF Site is selected show only site users
        /// </summary>
        /// <param name = "siteId"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        public ActionResult Index(int? siteId) {
            if (siteId.HasValue && siteId.Value > 0) _siteFilter = siteId;
            else if (siteId.HasValue && siteId.Value < 0) _siteFilter = null;

            var users = _siteFilter == null ? _service.GetAllUsers() : _service.GetSiteUsers(_siteFilter.Value);

            ViewBag.FilterOn = false;
            if (_siteFilter.HasValue) ViewBag.FilterOn = true;

            return View(users);
        }

        protected override void Initialize(RequestContext requestContext) {
            if (FormsService == null) {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null) {
                MembershipService = new AccountMembershipService();
            }

            base.Initialize(requestContext);
        }

        #region - Private Methods

        private void ValidateAppUserForm(AppUserModel user, bool isEdit) {
            if (string.IsNullOrWhiteSpace(user.UserName)) ModelState.AddModelError("UserName", "Invalid user name");
            if (string.IsNullOrWhiteSpace(user.Email)) ModelState.AddModelError("Email", "Invalid Email");
            if (string.IsNullOrWhiteSpace(user.FirstName)) ModelState.AddModelError("FirstName", "Missing first name");
            if (string.IsNullOrWhiteSpace(user.LastName)) ModelState.AddModelError("LastName", "Missing last name");

            if (!isEdit && (string.IsNullOrWhiteSpace(user.Password) || user.Password != user.ConfirmPassword)) {
                ModelState.AddModelError("Password", "Invalid Password");
                ModelState.AddModelError("ConfirmPassword", "Invalid Confirm Password");
                return;
            }
            // If we got this far, something failed, redisplay form
            if (!isEdit && MembershipService.MinPasswordLength > user.Password.Length) {
                ModelState.AddModelError("Password", "Invalid Password Length");
                return;
            }

            const string pattern =
                @"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$";
            var regex = new Regex(pattern, RegexOptions.IgnoreCase);
            if (user.Email == null) return;
            var matches = regex.Matches(user.Email);
            if (matches.Count == 0) {
                ModelState.AddModelError("Email", "Invalid Email format");
            }
        }

        #endregion
    }
}